package com.abc.util;

import cn.hutool.core.util.ObjectUtil;
import com.abc.exception.ErrorCode;
import com.abc.help.SessionHelper;
import com.abc.model.SessionModel;
import com.abc.service.SessionService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * 校验工具类
 * 提供各种业务校验方法
 */
public class ValidationUtil {

    /**
     * 校验会话是否存在且属于当前用户
     *
     * @param sessionService 会话服务
     * @param sessionId 会话ID
     * @return 校验结果Flux
     */
    public static Flux<Void> validateSession(SessionService sessionService, String sessionId) {
        try {
            // 校验用户信息
            String currentUser = SessionHelper.getUser();
            if (ObjectUtil.isEmpty(currentUser)) {
                return Flux.error(new IllegalArgumentException(ErrorCode.MSG_USER_NOT_LOGIN));
            }

            // 校验会话是否存在且属于当前用户
            SessionModel session = sessionService.getOne(Wrappers.<SessionModel>lambdaQuery()
                    .eq(SessionModel::getSessionId, sessionId)
                    .eq(SessionModel::getUsername, currentUser)
            );

            if (ObjectUtil.isEmpty(session)) {
                return Flux.error(new IllegalArgumentException(ErrorCode.MSG_SESSION_NOT_FOUND));
            }

            // 校验会话是否已被删除
            if (session.getDeleted() != null && session.getDeleted() == 1) {
                return Flux.error(new IllegalArgumentException(ErrorCode.MSG_SESSION_EXPIRED));
            }

            return Flux.empty();

        } catch (Exception e) {
            return Flux.error(new IllegalArgumentException("会话校验失败: " + e.getMessage()));
        }
    }

    /**
     * 校验消息内容
     *
     * @param message 消息内容
     * @return 校验结果Flux
     */
    public static Flux<Void> validateMessage(String message) {
        try {
            if (ObjectUtil.isEmpty(message)) {
                return Flux.error(new IllegalArgumentException(ErrorCode.MSG_CHAT_MESSAGE_EMPTY));
            }

            String trimmedMessage = message.trim();
            if (trimmedMessage.isEmpty()) {
                return Flux.error(new IllegalArgumentException(ErrorCode.MSG_CHAT_MESSAGE_EMPTY));
            }

            if (trimmedMessage.length() > 4000) {
                return Flux.error(new IllegalArgumentException(ErrorCode.MSG_CHAT_MESSAGE_TOO_LONG));
            }


            return Flux.empty();

        } catch (Exception e) {
            return Flux.error(new IllegalArgumentException("消息校验失败: " + e.getMessage()));
        }
    }

    /**
     * 校验会话ID格式
     *
     * @param sessionId 会话ID
     * @return 校验结果Flux
     */
    public static Flux<Void> validateSessionId(String sessionId) {
        try {
            if (ObjectUtil.isEmpty(sessionId)) {
                return Flux.error(new IllegalArgumentException("会话ID不能为空"));
            }

            String trimmedSessionId = sessionId.trim();
            if (trimmedSessionId.isEmpty()) {
                return Flux.error(new IllegalArgumentException("会话ID不能为空白字符"));
            }

            if (trimmedSessionId.length() < 10 || trimmedSessionId.length() > 64) {
                return Flux.error(new IllegalArgumentException("会话ID格式不正确"));
            }

            return Flux.empty();

        } catch (Exception e) {
            return Flux.error(new IllegalArgumentException("会话ID校验失败: " + e.getMessage()));
        }
    }

    /**
     * 检查是否包含敏感词
     *
     * @param message 消息内容
     * @return 是否包含敏感词
     */
    private static boolean containsSensitiveWords(String message) {
        // 简单的敏感词检测示例
        String[] sensitiveWords = {"违法", "色情", "暴力", "政治敏感", "赌博", "诈骗"};
        String lowerMessage = message.toLowerCase();

        for (String word : sensitiveWords) {
            if (lowerMessage.contains(word.toLowerCase())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 校验用户权限
     *
     * @return 校验结果Flux
     */
    public static Flux<Void> validateUserPermission() {
        try {
            String currentUser = SessionHelper.getUser();
            if (ObjectUtil.isEmpty(currentUser)) {
                return Flux.error(new IllegalArgumentException(ErrorCode.MSG_USER_NOT_LOGIN));
            }

            return Flux.empty();

        } catch (Exception e) {
            return Flux.error(new IllegalArgumentException("用户权限校验失败: " + e.getMessage()));
        }
    }

    /**
     * 综合校验聊天请求
     *
     * @param sessionService 会话服务
     * @param sessionId 会话ID
     * @param message 消息内容
     * @return 校验结果Mono
     */
    public static Mono<Void> validateChatRequest(SessionService sessionService, String sessionId, String message) {
        return Flux.concat(
                validateUserPermission(),
                validateSessionId(sessionId),
                validateMessage(message),
                validateSession(sessionService, sessionId)
        ).then();
    }
}
